package com.suitsoft.ut.web.group;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.utils.web.struts2.Struts2Utils;
import org.springside.modules.web.struts2.annotations.Token;

import com.google.common.collect.Lists;
import com.opensymphony.xwork2.ActionSupport;
import com.suitsoft.ut.commons.Constants;
import com.suitsoft.ut.commons.LogAnnotation;
import com.suitsoft.ut.commons.UserHolder;
import com.suitsoft.ut.entity.account.Role;
import com.suitsoft.ut.entity.account.User;
import com.suitsoft.ut.entity.base.College;
import com.suitsoft.ut.entity.base.Teacher;
import com.suitsoft.ut.entity.base.Team;
import com.suitsoft.ut.service.ServiceException;
import com.suitsoft.ut.service.account.AccountManager;
import com.suitsoft.ut.service.base.CollegeManager;
import com.suitsoft.ut.service.base.GroupManager;
import com.suitsoft.ut.service.base.TeacherManger;
import com.suitsoft.ut.web.CrudActionSupport;

/**
 * 分组
 *@author Suineg
 */
@Results({@Result(name = CrudActionSupport.RELOAD,location="group.action",type="redirect")})
public class GroupAction extends ActionSupport{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/** 日志输出对象 */
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	/** 小组 */
	private final String GROUP = "group";
	/** 成员 */
	private final String MEMBER = "member";
	/** 设置负责人 */
	@SuppressWarnings("unused")
	private final String MASTER = "master";
	
	private GroupManager groupManager;
	private CollegeManager collegeManager;
	private TeacherManger teacherManger;
	private AccountManager accountManager;
	
	private Page<Team> page = new Page<Team>(Constants.PAGE_SIZE);
	private Team team;
	private Long id;
	private Long subId;
	/** 学院名 */
	private String collegeName;
	private List<Long> checkedTeachers;
	private List<College> collegeList;
	private Long collegeId;
	
	@Override
	public String execute() {
		//设置默认排序方式
		if (!page.isOrderBySetted()) {
			page.setOrderBy("groupName");
			page.setOrder(Page.ASC);
		}
		groupManager.findAllByCollege(page,UserHolder.getLoginUser().getCollegeCode());
		return SUCCESS;
	}

	public String input(){
		collegeList = collegeManager.getByUser();
		if(id == null || id == 0l){
			return INPUT;
		}
		team = groupManager.get(id);
		return INPUT;
	}
	@LogAnnotation(log = "团队管理 - 保存团队")
	@Token
	public String save(){
		if(team == null || collegeId == null || collegeId == 0l){
			addActionMessage("非法操作！");
			return SUCCESS;
		}
		College college = collegeManager.get(collegeId);
		team.setCollege(college);
		groupManager.save(team);
		addActionMessage("保存成功！");
		return CrudActionSupport.RELOAD;
	}
	@LogAnnotation(log = "团队管理 - 删除")
	public String del(){
		if(id == null || id == 0l){
			addActionMessage("非法操作！");
			return SUCCESS;
		}
		groupManager.delete(id);
		addActionMessage("操作成功！");
		return CrudActionSupport.RELOAD;
	}
	/*
	 * 小组
	 */
	public String group(){
		if(subId == null || subId == 0l){
			addActionMessage("非法操作!");
			return SUCCESS;
		}
		String subGroup = groupManager.get(subId).getGroupName();
		if(id == null || id == 0l){
			team = new Team();
			Team t = new Team();
			t.setGroupName(subGroup);
			team.setSubTeam(t);
		}else{
			team = groupManager.get(id);
		}
		collegeList = collegeManager.getByUser();
		return GROUP;
	}
	
	@Token
	@LogAnnotation(log = "团队管理 - 小组保存")
	public String gruopSave(){
		if(subId == null || subId == 0l ||collegeId == null ||collegeId == 0l){
			addActionMessage("非法操作！");
			return SUCCESS;
		}
		College college = collegeManager.get(collegeId);
		Team t = groupManager.get(subId);
		team.setSubTeam(t);
		team.setCollege(college);
		
		groupManager.save(team);
		addActionMessage("保存成功！");
		return CrudActionSupport.RELOAD;
	}
	
	@LogAnnotation(log = "团队管理 - 小组删除")
	public String groupDel(){
		if(id == null || id == 0l){
			addActionMessage("非法操作！");
			return SUCCESS;
		}
		try {
			groupManager.delete(id);
		} catch (Exception e) {
			e.printStackTrace();
			addActionMessage("删除失败！");
			return CrudActionSupport.RELOAD;
		}
		addActionMessage("删除成功！");
		return CrudActionSupport.RELOAD;
	}
	
	/***
	 * 查看及编辑成员
	 * @return
	 */
	public String member(){
		if(id == null || id == 0l){
			addActionMessage("非法操作！");
			return SUCCESS;
		}
		team = groupManager.get(id);
		
		return MEMBER;
	}
	
	@Token
	@LogAnnotation(log = "团队管理 - 保存成员！")
	public String memberSave(){
		if(id == null || id == 0l){
			addActionMessage("非法操作!");
			return CrudActionSupport.RELOAD;
		}
		team = groupManager.get(id);
		
		
		User user = null;
		List<Role> roleList = getTeamRole(team);
		
		
		if(roleList != null && !roleList.isEmpty()){
			cleanOldTeacherRole(team,roleList);
		}
		
		if(checkedTeachers == null || checkedTeachers.isEmpty()){
			addActionMessage("清空成功！");
			return CrudActionSupport.RELOAD;
		}
		
		
		List<Teacher> teachers = teacherManger.get(checkedTeachers);
		//给每个被先的用户赋予相应的权限
		//给教师与团队建立联系
		for(Teacher t : teachers){
			user = t.getForUser();
			user.getRoleList().addAll(resetRoleList(user.getRoleList(), roleList));
			accountManager.saveUser(user);
			
			t.getTeamList().add(team);
			teacherManger.save(t);
		}
		
		addActionMessage("操作成功！");
		
		return CrudActionSupport.RELOAD;
	}
	
	/**
	 * 整理权限 列表
	 * <pre>把那些重复的去掉</pre>
	 * @param yuanshi
	 * @param roleList
	 * @return
	 */
	private List<Role> resetRoleList(List<Role> yuanshi,List<Role> roleList){
		//原始列表
		List<Role> oldList = Lists.newArrayList();
		oldList.addAll(yuanshi);
		
		List<Role> tempList = Lists.newArrayList();
		//复制
		tempList.addAll(oldList);
		//保留重复部分
		tempList.retainAll(roleList);
		if(tempList.size() == 0){
			return roleList;
		}else{
			//去掉重复部分
			oldList.removeAll(tempList);
			return oldList;
		}
		
	}
	
	/**
	 * 清除旧教师的权限
	 * @param team
	 */
	private void cleanOldTeacherRole(Team team,List<Role> roleList){
		for(Teacher t : team.getTeacherList()){
			User user = t.getForUser();
			user.getRoleList().removeAll(roleList);
			accountManager.saveUser(user);
	//		t.setTeam(null);
			teacherManger.save(t);
			removeMastersRole(user);
			
		}
		team.setTeacherList(null);
		team.setMaster(null);
		groupManager.save(team);
	}
	
	/**
	 * 获取教师信息(用于Ajax)
	 * ID和名
	 */
	public void getTeacher(){
		try {
			PrintWriter out = Struts2Utils.getResponse().getWriter();
			List<College> list = collegeManager.findByName(collegeName);
			JSONArray array = new JSONArray();
			List<Map<String,Object>> resutList = new ArrayList<Map<String,Object>>();
			if(list != null && !list.isEmpty()){
				for(College college : list){
					Map<String,Object> map = null;
					for(Teacher t : college.getTeachers()){
						map = new HashMap<String,Object>();
						map.put("name", t.getTeacherName() + " (" + t.getTeacherNo() + ")");
						map.put("id", t.getId());
						resutList.add(map);
					}
				}
				array = JSONArray.fromObject(resutList);
			}
			out.print(array.toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * 设置负责人 Ajax初始化
	 * @return
	 */
	public void master(){
		try {
			PrintWriter out = Struts2Utils.getResponse().getWriter();
			if(id != null && id != 0l){
				JSONArray array = new JSONArray();
				try {
					team = groupManager.get(id);
					array = new JSONArray();
					JSONObject obj = null;
					for(Teacher t : team.getTeacherList()){
						obj = new JSONObject();
						obj.put("id", t.getId());
						obj.put("name", t.getTeacherName() + "(" + t.getTeacherNo() + ")");
						if(team.getMaster() != null ){
							if(team.getMaster().getId().equals(t.getId())){
								obj.put("isMaster", Constants.IS_MASTER_YES);
							}else{
								obj.put("isMaster", Constants.IS_MASTER_NO);
							}
						}else{
							obj.put("isMaster", Constants.IS_MASTER_NO);
						}
						array.add(obj);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				out.print(array.toString());
				out.flush();
				out.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@LogAnnotation(log = "团队管理  - 设置团队负责人")
	public void saveMaster(){
		String msg = "操作失败！";
		try {
			PrintWriter out = Struts2Utils.getResponse().getWriter();
			if(id != null && id != 0l){
				Teacher teacher = teacherManger.get(id);
				for(Team t :teacher.getTeamList()){
					if(t.getId().equals(subId)){
						team = t;
						break;
					}
				}
				
				if(team.getId().equals(subId)){
					//设置负责人
					team.setMaster(teacher);
					//给负责人赋予权限
					setRole(team,teacher);
					msg = "";
				}
			}
			out.print(msg);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		team = groupManager.get(id);
		
	}
	
	/**
	 * 团队的角色集
	 * @param team
	 * @return
	 */
	public List<Role> getTeamRole(Team team){
		List<Role> roleList = null;
		//判断当前是哪类,并获取角色
		if(Constants.TEAM_TYPE_LITI.equals(Integer.valueOf(team.getType()))){
			roleList = accountManager.findRoleByGroupName(Constants.CN_LITI);
		}else if(Constants.TEAM_TYPE_SHENTI.equals(Integer.valueOf(team.getType()))){
			roleList = accountManager.findRoleByGroupName(Constants.CN_KAITI);
		}else if(Constants.TEAM_TYPE_MIDDLE.equals(Integer.valueOf(team.getType()))){
			roleList = accountManager.findRoleByGroupName(Constants.CN_MIDDLE);
		}else if(Constants.TEAM_TYPE_DABIAN.equals(Integer.valueOf(team.getType()))){
			roleList = accountManager.findRoleByGroupName(Constants.CN_DABIAN);
		}
		return roleList;
	}
	
	/**
	 * 团队的负责人角色集
	 * @param team
	 * @return
	 */
	public List<Role> getTeamMastRole(Team team){
		List<Role> roleList = null;
		//判断当前是哪类,并获取角色
		if(Constants.TEAM_TYPE_LITI.equals(Integer.valueOf(team.getType()))){
			roleList = accountManager.findRoleByGroupName(Constants.CN_TIME_MASTER_LITI);
		}else if(Constants.TEAM_TYPE_SHENTI.equals(Integer.valueOf(team.getType()))){
			roleList = accountManager.findRoleByGroupName(Constants.CN_TIME_MASTER_KAITI);
		}else if(Constants.TEAM_TYPE_MIDDLE.equals(Integer.valueOf(team.getType()))){
			roleList = accountManager.findRoleByGroupName(Constants.CN_TIME_MASTER_MIDLLE);
		}else if(Constants.TEAM_TYPE_DABIAN.equals(Integer.valueOf(team.getType()))){
			roleList = accountManager.findRoleByGroupName(Constants.CN_TIME_MASTER_DABIAN);
		}
		return roleList;
	}
	
	
	/**
	 * 设置负责人的权限
	 */
	public void setRole(Team team,Teacher teacher){
		//判断当前是哪类,并获取角色
		List<Role> roleList = getTeamMastRole(team);
		if(roleList == null || roleList.isEmpty()){
			throw new ServiceException("内置角色不存在！");
		}
		Role role = roleList.get(0);
		for(Teacher t : team.getTeacherList()){
			User user = t.getForUser();
			
	//		user = removeMastersRole(user);
			accountManager.saveUser(user);
			
		}
		
		User checkUser = teacher.getForUser();
		checkUser.getRoleList().add(role);
		accountManager.saveUser(checkUser);
	}
	/**
	 * 清除用户的所有团队负责人的角色
	 * @param user
	 */
	public User removeMastersRole(User user){
		List<Role> newRoles = new ArrayList<Role>();
		List<Role> roles = null;
		roles = accountManager.findRoleByGroupName(Constants.CN_TIME_MASTER_LITI);
		if(roles != null && !roles.isEmpty()){
			newRoles.add(roles.get(0));
		}
		
		roles = accountManager.findRoleByGroupName(Constants.CN_TIME_MASTER_KAITI);
		if(roles != null && !roles.isEmpty()){
			newRoles.add(roles.get(0));
		}
		
		roles = accountManager.findRoleByGroupName(Constants.CN_TIME_MASTER_MIDLLE);
		if(roles != null && !roles.isEmpty()){
			newRoles.add(roles.get(0));
		}
		
		roles = accountManager.findRoleByGroupName(Constants.CN_TIME_MASTER_DABIAN);
		if(roles != null && !roles.isEmpty()){
			newRoles.add(roles.get(0));
		}
		if(!newRoles.isEmpty()){
			user.getRoleList().removeAll(newRoles);
			accountManager.saveUser(user);
		}
		return user;
	}
	
	public Page<Team> getPage() {
		return page;
	}
	@Autowired
	public void setGroupManager(GroupManager groupManager) {
		this.groupManager = groupManager;
	}

	public void setPage(Page<Team> page) {
		this.page = page;
	}

	public Team getTeam() {
		return team;
	}

	public void setTeam(Team team) {
		this.team = team;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}
	public Long getSubId() {
		return subId;
	}
	public void setSubId(Long subId) {
		this.subId = subId;
	}

	public String getCollegeName() {
		return collegeName;
	}

	public void setCollegeName(String collegeName) {
		this.collegeName = collegeName;
	}
	@Autowired
	public void setCollegeManager(CollegeManager collegeManager) {
		this.collegeManager = collegeManager;
	}

	public List<Long> getCheckedTeachers() {
		return checkedTeachers;
	}

	public void setCheckedTeachers(List<Long> checkedTeachers) {
		this.checkedTeachers = checkedTeachers;
	}
	@Autowired
	public void setTeacherManger(TeacherManger teacherManger) {
		this.teacherManger = teacherManger;
	}
	@Autowired
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}

	public List<College> getCollegeList() {
		return collegeList;
	}
	public void setCollegeList(List<College> collegeList) {
		this.collegeList = collegeList;
	}
	public Long getCollegeId() {
		return collegeId;
	}
	public void setCollegeId(Long collegeId) {
		this.collegeId = collegeId;
	}
}

